
const install = (Vue, vm) => {
	
	let contime = 0
	const $socket = {
		// 初始化WebSocket连接
		initWebSocket() {
			// 创建连接
			uni.connectSocket({
				// 测试换
				url: 'ws://119.254.149.75:8054/websocket',
				// 演示环境
				// url: 'ws://119.254.149.75:8055/websocket',
				complete: () => {}
			})
			// 监听WebSocket连接打开事件
			uni.onSocketOpen(res => {
				// 读取缓存的token
				const token = vm.$store.state.vuex_token
				// socket连接状态设置为true
				vm.$u.vuex('socket_state', true)
				console.log('websocket已连接！')
				// 构建初始化消息
				contime = 0
				const msg = JSON.stringify({
					method: "OnConnection",
					token: token,
					mobileDevice: true
				})
				// 发送初始化消息
				this.sendMessage(msg)
			})
			// 监听WebSocket错误
			uni.onSocketError(err => {
				// socket连接状态设置为false
				vm.$u.vuex('socket_state', false)
				
			})
			// 监听
			uni.onSocketMessage(res => {
				const data = JSON.parse(res.data)
				console.log(data)
				switch (data.method){
					case 'initMessage' : // 初始化
						vm.$u.vuex('notice_msg_def', data)
						if(data.unreadNoticeCount > 0 || data.unreadMessageCount > 0) {
							uni.showTabBarRedDot({index:1})
						} else {
							uni.hideTabBarRedDot({index:1})
						}
						break;
					default:
						break;
				}
				
			})
		},
		sendMessage(msg) {
			uni.sendSocketMessage({
				data: msg,
				fail: (e) => {
					this.reConnect();
				}
			});
		},
		reConnect() {
			this.initWebSocket()
		}
	}
	
	Vue.prototype.$socket = $socket
}

export default {
	install
}
